package com.taikang.hmp.hbusiness.doctor.setbase.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import sun.misc.BASE64Decoder;

import com.taikang.hmp.frame.common.TKException;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.properties.PropertiesHandler;
import com.taikang.hmp.frame.common.properties.PropertiesHandlerFactory;
import com.taikang.hmp.frame.common.service.impl.BaseServiceImpl;
import com.taikang.hmp.frame.common.tools.ImgErToFileUtil;
import com.taikang.hmp.frame.common.web.session.SessionBean;
import com.taikang.hmp.frame.customer.bean.CustomerInfo;
import com.taikang.hmp.frame.user.bean.AuthUserInfo;
import com.taikang.hmp.hbusiness.doctor.register.bean.Activation;
import com.taikang.hmp.hbusiness.doctor.setbase.service.IUserBaseService;

public class UserBaseServiceImpl extends BaseServiceImpl implements IUserBaseService {
	
	public static PropertiesHandler appHelper = PropertiesHandlerFactory.getPropertiesHelper("app");
	/**
	 * 保存客户基本信息
	 */
	public void saveBasicInfo(Dto dto) {
//		Map<String,String> map = new HashMap<String,String>();
//		map.put("uid", dto.getAsString("uid"));
//		map.put("mobile", dto.getAsString("mobile"));
		//String uid = dto.getAsString("uid");
		///AuthUserInfo aui = new AuthUserInfo();
		//aui.setUser_id(uid);
		//aui.setUser_type(dto.getAsString("usertype"));
		//aui.setUser_name(dto.getAsString("mobile"));
//		super.getNewDao().update("hd_user_space.update_authUserInfo", map);
		AuthUserInfo authUserInfo = (AuthUserInfo)super.getNewDao().queryForObject("hd_user_space.authInfo_uid", dto.getAsString("uid"));
		CustomerInfo ci = new CustomerInfo();
		ci.setCustomer_id(authUserInfo.getCustom_id());
//		ci.setMobile(dto.getAsString("mobile"));
		ci.setName(dto.getAsString("name"));
		ci.setBirthday(dto.getAsString("birthday"));
		ci.setSex(dto.getAsString("sex"));
		ci.setHeight(dto.getAsString("height"));
		ci.setWeight(dto.getAsString("weight"));
		ci.setSource_cd(dto.getAsString("requestsource"));
		super.getNewDao().update("hd_user_space.update_customerInfo", ci);
	}
	
	
	/**
	 * 获取客户基本信息
	 */
	public SessionBean getCustomerBasicInfo(String uid, SessionBean sessionBean) {
		if(sessionBean!=null){
			sessionBean = new SessionBean();
		}
		List<AuthUserInfo> info  = super.getNewDao().queryForList("hd_user_space.authInfo_uid", uid);
		if(info==null || info.isEmpty()){
			throw new TKException("userid:"+uid+"无对应用户信息");
		}
		List<CustomerInfo> info1 = super.getNewDao().queryForList("hd_user_space.getCustomer_uid", uid);
		if(info1==null || info1.isEmpty()){
			throw new TKException("userid:"+uid+"无对应客户信息");
		}
		sessionBean.setAuthUserInfo(info.get(0));
		sessionBean.setCustomerInfo(info1.get(0));
		return sessionBean;
	}
	
	
	
	/**
	 * 校验密码
	 */
	public boolean check_password_true(Dto paramDto) {
		String uid = paramDto.getAsString("uid");
		List<AuthUserInfo> info  = super.getNewDao().queryForList("hd_user_space.authInfo_uid", uid);
		if(info.get(0).getUser_pwd().equals(paramDto.getAsString("password"))){
			return  true;//正确
		}else{
			return false;//不正确 
		}
	}
	
	
	/**
	 * 更新密码
	 */
	public void updatePassword(Dto paramDto) {
		AuthUserInfo au = new AuthUserInfo();
		au.setUser_id(paramDto.getAsString("uid"));
		au.setUser_pwd(paramDto.getAsString("newpassword"));
		super.getNewDao().update("hd_user_space.upate_password",au);
	}
	

	
	/**
	 * 我的服务数据
	 */
	public List<Dto> getServiceDate(String uid) {
		List<Dto> result = new ArrayList<Dto>();
		Dto resultMap = new BaseDto();
		List<CustomerInfo> info = super.getNewDao().queryForList("hd_user_space.getCustomer_uid", uid);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if(info.get(0).getActivation_code() != null && info.get(0).getActivation_code().length() != 0) {
		resultMap.put("startDate", format.format(info.get(0).getFirstdate()));
		resultMap.put("endDate", format.format(info.get(0).getLastdate()));
		
			resultMap.put("status", "1");
		}else{
			resultMap.put("status", "0");
		}
		result.add(resultMap);
		return result;
	}

	
	/**
	 * 激活码是否存在
	 */
	public Integer check_activationcode_exist(String activationcode) {
		
		//查找激活码
		Object activationcodeInfo = super.getNewDao().queryForObject("hd_user_space.check_activationcode_exist", activationcode);
		
		if(activationcodeInfo == null){
			return 2;//不存在
		}else{
			String actString = (String)activationcodeInfo;
		    if(actString.equals("0")){
				return 0;//可用
			}else if(actString.equals("1")){
				return 1;//已使用
			}else{
				return 3;//不正常
			}
		}
			
	}
	
	
	/**
	 * 更新用户真实姓名
	 */
	public void updateCustomerInfo(CustomerInfo customerInfo) {
		super.getNewDao().update("hd_user_space.update_customerInfo", customerInfo);
	}
	
	/**
	 * 更新用户UCM激活时间
	 */
	public void updateCustomerUCM(CustomerInfo customerInfo) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, String> info = new HashMap<String, String>();
		info.put("activity_time",format.format(new Date()) );
		info.put("customer_id", customerInfo.getCustomer_id());
		super.getNewDao().update("hd_user_space.update_customerInfo_UCM", info);
		super.getNewDao().update("hd_user_space.update_customerInfo_IM", info);
	}
	
	
	
	/**
	 * 更新激活码
	 */
	public void saveActivation(Dto paramDto) {
		//当前时间 +一年的时间 激活服务时间
		Calendar calendar = Calendar.getInstance();
        Date date = new Date(System.currentTimeMillis());
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1);
        date = calendar.getTime();
		System.out.println("一年以后："+date);
		//更新customer
		String customerid = getCustomerIdByUid(paramDto.getAsString("uid"));
		CustomerInfo ci = new CustomerInfo();
		ci.setCustomer_id(customerid);
		ci.setActivation_code(paramDto.getAsString("code").toUpperCase());
		ci.setFirstdate(new Date());
		ci.setLastdate(date);
		System.out.println("用户："+ci.toString());
		super.getNewDao().update("hd_user_space.update_customerInfo_activation", ci);
		//更新activation
		Activation ac = new Activation();
		ac.setCustom_id(customerid);
		ac.setActivation_code(paramDto.getAsString("code").toUpperCase());
		ac.setLast_date(date);
		ac.setIs_uesd("1");
		ac.setOperate_date(new Date());
		ac.setSource_cd(paramDto.getAsString("requestsource"));
		ac.setOperater(paramDto.getAsString("uid"));
		super.getNewDao().update("hd_user_space.update_activation", ac);
	}
	//
	private String getCustomerIdByUid(String uid) {
		if(StringUtils.isEmpty(uid)){
			throw new TKException("uid must not be null!");
		}
		
		List<CustomerInfo> customerIdList = super.getNewDao().queryForList("hd_user_space.getCustomer_uid", uid);
		if (customerIdList == null || customerIdList.isEmpty() || StringUtils.isEmpty(customerIdList.get(0).getCustomer_id()))		{
			throw new TKException("custumer id is not exist");
		}
		
		return customerIdList.get(0).getCustomer_id();
	}

	public boolean saveHeadImage(Dto paramDto) {
		//获取参数
		String savePath = appHelper.getValue("images.savePath");
		String getPath = appHelper.getValue("images.getPath");
		String new_icon = paramDto.getAsString("icon");
		String customerid = getCustomerIdByUid(paramDto.getAsString("uid"));
		//头像处理
//		String imgName = new Date().getTime() +".jpg";
		
		//TODO 屏蔽头像功能 modify by wangfugang 2015-11-26		
		String imgName = "defaultIcon.jpg";
		
		BASE64Decoder decoder = new BASE64Decoder();
		String tempstr = "";
		ImgErToFileUtil imageUtil = new ImgErToFileUtil();
		try {
			tempstr = imageUtil.byte2hex(decoder.decodeBuffer(new_icon));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
//		int result = imageUtil.saveToImgByStr(tempstr, savePath, imgName);
		
		//TODO 屏蔽头像功能 modify by wangfugang 2015-11-26	
		int result = 1;
		
		if(result == 1){
			String imageUrl = getPath+imgName;
			CustomerInfo ci = new CustomerInfo();
			ci.setCustomer_id(customerid);
			ci.setHead_image(imageUrl);
			super.getNewDao().update("hd_user_space.updateHeadUrl", ci);
			return true;
		}else{
			return false;
		}
	}

	public boolean saveImage(Dto paramDto) {
		//获取参数
		String savePath = appHelper.getValue("images.savePath");
		String getPath = appHelper.getValue("images.getPath");
		String new_icon = paramDto.getAsString("icon");
		String customerid = getCustomerIdByUid(paramDto.getAsString("uid"));
		//头像处理
//		String imgName = new Date().getTime() +".jpg";
		
		//TODO 屏蔽头像功能 modify by wangfugang 2015-11-26		
		String imgName = "defaultIcon.jpg";
		
		String temp = (new_icon.substring(1, new_icon.length()-1)).replaceAll(" ", "");
		
		ImgErToFileUtil imageUtil = new ImgErToFileUtil();
		
		
//		int result = imageUtil.saveToImgByStr(temp, savePath, imgName);
		
		//TODO 屏蔽头像功能 modify by wangfugang 2015-11-26	
		int result = 1;
		
		if(result == 1){
			String imageUrl = getPath+imgName;
			CustomerInfo ci = new CustomerInfo();
			ci.setCustomer_id(customerid);
			ci.setHead_image(imageUrl);
			super.getNewDao().update("hd_user_space.updateHeadUrl", ci);
			return true;
		}else{
			return false;
		}
	}
	

}
